package com.smec.moblie.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.smec.moblie.R;
import com.smec.moblie.SMECApplication;
import com.smec.moblie.activity.MainActivity;
import com.smec.moblie.adapter.MainListAdapter;
import com.smec.moblie.bean.Gps;
import com.smec.moblie.bean.MaintenanceBean;
import com.smec.moblie.bean.MaintenanceDetailBean;
import com.smec.moblie.bean.MaintenancePhotoJobitemBean;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.control.MainControl;
import com.smec.moblie.location.ServiceUtil;
import com.smec.moblie.util.Util;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

public class MaintenanceListFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    /**
     * 列表
     **/
    private ListView listView_order;
    /**
     * 下拉刷新控件
     **/
    private SwipeRefreshLayout refreshLayout;
    /**
     * 是否是已完成列表
     **/
    private boolean isfinished = false;
    /**
     * 是否正在刷新
     **/
    private boolean isRefresh = false;
    /**
     * 是否需要网络刷新
     **/
    private boolean needRefresh = false;
    /**
     * 是否能再加载更多（item是否已全部加载完成）
     **/
    private boolean canLordMore = true;
    /**
     * 选择的月份
     **/
    private String sel_month = "ALL";
    /**
     * 选择的日期
     **/
    private String sel_date;
    /**
     * 弹出的对话框
     **/
    private Dialog dialog;
    /**
     * 保养列表
     */
    private ArrayList<MaintenanceBean> maintenanceBeanList = new ArrayList<MaintenanceBean>();
    /**
     * 照片项
     */
    private ArrayList<MaintenancePhotoJobitemBean> maintenancePhotoJobitemBeanList = new ArrayList<MaintenancePhotoJobitemBean>();
    /**
     * 保养详情
     */
    private ArrayList<MaintenanceDetailBean> maintenanceDetailBeanList = new ArrayList<MaintenanceDetailBean>();
    private MainListAdapter mainListAdapter;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    /***
     * 获取主页列表
     * 获取拍照项
     */
    private class getMainList extends AsyncTask<Void, Void, Void> {
        String workorder_id = "0";
        boolean isSuccess = true;
        String errString;

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            try {
                if (isSuccess) {
                    mainListAdapter.setList(maintenanceBeanList);
                    EventBus.getDefault().post(new EventCenter.ChangeLeftItems());
                } else {
                    Toast.makeText(getActivity(), "数据加载失败，请检查网络状况是否良好,错误信息：" + errString, Toast.LENGTH_LONG).show();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                }
            });
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            isRefresh = true;
            try {
                int maintenanceBeanListnum = DataSupport.where("assignee = ?", MainActivity.USERNAME).limit(3).count(MaintenanceBean.class);
                int photonum = DataSupport.where("assignee = ?", MainActivity.USERNAME).limit(3).count(MaintenancePhotoJobitemBean.class);
                if (maintenanceBeanListnum > 0 && photonum > 0 && !needRefresh) {

                } else {
                    if (maintenanceBeanListnum > 0) {
                        MaintenanceBean maintenanceBean = DataSupport.order("MNT_SCH_DATE ASC").findLast(MaintenanceBean.class);
                        workorder_id = maintenanceBean.getWorkorder_id();
                    }
                    if (photonum == 0) {
                        workorder_id = "0";
                    }
                    try {
                        MainControl.getMaintenancePhotoJobitem(MainActivity.USERNAME, workorder_id);//拍照项
                        MainControl.getMaintenanceDetail(MainActivity.USERNAME);//详情信息
                        MainControl.getAllPhotoData(MainActivity.USERNAME);//照片数据
                        MainControl.getFastRepairHis(MainActivity.USERNAME);//急修历史
                        MainControl.getMemos(MainActivity.USERNAME);//电梯备忘
                        MainControl.getMaintenanceList(MainActivity.USERNAME, workorder_id);//主页列表

                        isSuccess = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        isSuccess = false;
                        errString = e.getMessage();
                    }
                }
                if (isfinished) {
                    maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("wo_status_code = 'COMPLETED' AND assignee = ?", MainActivity.USERNAME).order("workorder_id desc").find(MaintenanceBean.class);
                } else {
                    //未完成当天的显示在最前面
                    maintenanceBeanList = new ArrayList<MaintenanceBean>();
                    maintenanceBeanList.addAll(DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE like ? ", MainActivity.USERNAME, "%" + Util.getSystemDateDD() + "%").find(MaintenanceBean.class));
//                    if (maintenanceBeanList.size() < 10) {
                    maintenanceBeanList.addAll(DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE not like ?", MainActivity.USERNAME, "%" + Util.getSystemDateDD() + "%").order("workorder_no asc").find(MaintenanceBean.class));
//                    }
                }

            } catch (Exception e) {
                isSuccess = false;
                e.printStackTrace();
                errString = e.getMessage();
            }
            isRefresh = false;
            return null;
        }

    }


    public void onRefreshView() {

        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        new getMainList().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_maintenance, container, false);
        EventBus.getDefault().register(this);//注册EventBus
        listView_order = (ListView) view.findViewById(R.id.listView_order);
        refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.GREEN, Color.BLUE, Color.YELLOW);
        refreshLayout.setDistanceToTriggerSync(400);

        mainListAdapter = new MainListAdapter(getActivity());
        mainListAdapter.setList(maintenanceBeanList);
        listView_order.setAdapter(mainListAdapter);

        Bundle bundle = getActivity().getIntent().getExtras();
        if (null != bundle) {
            String title = bundle
                    .getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
            if (null != title && !"".equals(title)) {
                needRefresh = true;
            }
        }

        onRefreshView();
        return view;
    }

    @Override
    public void onRefresh() {
        if (!isRefresh) {
            needRefresh = true;
            new getMainList().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    //获取是否是保养已完成工单
    @Subscribe
    public void onEventMainThread(EventCenter.ChangeIsFinsish event) {
        isfinished = event.getIsFinished();
        needRefresh = false;
        canLordMore = true;
        refreshLayout.setEnabled(true);

        new getMainList().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    //地图返回数据
    @Subscribe
    public void onEventMainThread(EventCenter.MapBack event) {
        final int position = event.getPosition();
        if (position != -1) {
            final Gps gps = event.getMapBack();

            double longitude;
            double latitude;
            try {
                longitude = Double.parseDouble(maintenanceBeanList.get(position).getLongitude());
                latitude = Double.parseDouble(maintenanceBeanList.get(position).getLatitude());
            } catch (Exception e) {
                longitude = 0;
                latitude = 0;
            }
            try {
//                Boolean isArrived = ServiceUtil.getCachelocation(getActivity(), longitude + "", latitude + "");
                Boolean isArrived = false;
                if (longitude != 0 && latitude != 0) {
                    isArrived = ServiceUtil.getCachelocation(getActivity(), longitude + "", latitude + "");

                } else {
                    isArrived = true;

                    MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                    maintenanceBeanTemp.setArrive_status(NO_COORDINATE);
                    maintenanceBeanTemp.setIsDirty(1);

                    maintenanceBeanTemp.update(maintenanceBeanList.get(position).getId());
                    maintenanceBeanList.get(position).setIsDirty(1);

//                    Toast.makeText(getActivity(), "当前电梯没有项目坐标，请通知站长维护(工单流程不受此影响，将会继续提交)", Toast.LENGTH_LONG).show();
                }
                if (!isArrived) {
                    new AlertView("提示", "未到达电子围栏内，确认要到达？", "取消", new String[]{"确定"}, null, getActivity(),
                            AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int p) {
                            if (p == 0) {
                                arrivedChange(gps, position);
                            }
                        }
                    }).show();
                } else {
                    arrivedChange(gps, position);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 到达现场
     *
     * @param gps
     * @param position
     */
    private void arrivedChange(Gps gps, int position) {
        MaintenanceBean maintenanceBean = maintenanceBeanList.get(position);
        maintenanceBean.setOnsite_date(Util.getSystemDateNow());
        maintenanceBean.setOrderCode(ORDER_SUBMITINFORMATION);
        maintenanceBean.setOnsite_longitude(gps.getWgLon() + "");
        maintenanceBean.setOnsite_latitude(gps.getWgLat() + "");
        maintenanceBean.setIsDirty(1);
        maintenanceBean.update(maintenanceBean.getId());
        MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
        maintenanceBeanTemp.setOnsite_date(Util.getSystemDateNow());
        maintenanceBeanTemp.setOrderCode(ORDER_SUBMITINFORMATION);
        maintenanceBeanTemp.setOnsite_longitude(gps.getWgLon() + "");
        maintenanceBeanTemp.setOnsite_latitude(gps.getWgLat() + "");
        maintenanceBeanTemp.setIsDirty(1);
        maintenanceBeanTemp.update(maintenanceBean.getId());

        mainListAdapter.setList(maintenanceBeanList);
        EventBus.getDefault().post(new EventCenter.UpdateTime(maintenanceBean));
        displayBaffle();
    }

    //弹出挡板
    @Subscribe
    public void onEventMainThread(EventCenter.showBaffleDialog event) {
        displayBaffle();
    }


    /**
     * 弹出挡板
     */
    public void displayBaffle() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_put_baffle, null);

        dialog = new AlertDialog.Builder(getActivity())
                .setTitle("放置挡板并拍照").setView(view)
                .setCancelable(false).create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog,
                                 int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        ImageView imageView_takePhoto = (ImageView) view
                .findViewById(R.id.imageView_takePhoto);
        imageView_takePhoto
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent,
                                CAMERA_DANGBAN);
                    }
                });
        dialog.show();
    }

    //选择月份
    @Subscribe
    public void onEventMainThread(EventCenter.SelectMonth event) {
        sel_month = event.getMonth();
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        new MonthSelectAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    /**
     * 选择月份筛选list
     */
    private class MonthSelectAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            if (sel_month.equals("ALL")) {
                if (isfinished) {
                    maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("wo_status_code = 'COMPLETED' AND assignee = ?", MainActivity.USERNAME).find(MaintenanceBean.class);
                } else {
                    //未完成当天的显示在最前面
                    maintenanceBeanList = new ArrayList<MaintenanceBean>();
                    maintenanceBeanList.addAll(DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE like ? ", MainActivity.USERNAME, "%" + Util.getSystemDateDD() + "%").find(MaintenanceBean.class));
//                    if (maintenanceBeanList.size() < 10) {
                    maintenanceBeanList.addAll(DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE not like ?", MainActivity.USERNAME, "%" + Util.getSystemDateDD() + "%").find(MaintenanceBean.class));
//                    }
                }
                canLordMore = true;
            } else {

                if (isfinished) {
                    maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("wo_status_code = 'COMPLETED' AND assignee = ? AND MNT_SCH_DATE >= ? AND MNT_SCH_DATE < ?", MainActivity.USERNAME, sel_month, sel_month + "/32").find(MaintenanceBean.class);
                } else {
                    maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE >= ? AND MNT_SCH_DATE < ?", MainActivity.USERNAME, sel_month, sel_month + "/32").find(MaintenanceBean.class);
                }
                canLordMore = false;
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mainListAdapter.setList(maintenanceBeanList);
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                }
            });
            if (sel_month.equals("ALL")) {
                refreshLayout.setEnabled(true);
            } else {
                refreshLayout.setEnabled(false);
            }
            super.onPostExecute(aVoid);
        }
    }

    //筛选日期
    @Subscribe
    public void onEventMainThread(EventCenter.SelectDate event) {
        sel_date = event.getDate();
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        new DateSelectAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    /**
     * 日期筛选
     */
    private class DateSelectAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            if (isfinished) {
                maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("wo_status_code = 'COMPLETED' AND assignee = ? AND MNT_SCH_DATE like ? ", MainActivity.USERNAME, "%" + sel_date + "%").find(MaintenanceBean.class);
            } else {
                maintenanceBeanList = (ArrayList<MaintenanceBean>) DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG' OR wo_status_code = 'STATION_REJECT') AND assignee = ? AND MNT_SCH_DATE like ? ", MainActivity.USERNAME, "%" + sel_date + "%").find(MaintenanceBean.class);
            }
            canLordMore = false;
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mainListAdapter.setList(maintenanceBeanList);
            refreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    refreshLayout.setRefreshing(false);
                }
            });
            refreshLayout.setEnabled(false);
            super.onPostExecute(aVoid);
        }
    }

    /**
     * 上传时间
     */
    private class UpdateTimeAsyncTask extends AsyncTask<Void, Void, Void> {
        private MaintenanceBean maintenanceBean;

        public UpdateTimeAsyncTask(MaintenanceBean maintenanceBean) {
            this.maintenanceBean = maintenanceBean;
        }

        @Override
        protected Void doInBackground(Void... params) {
            //上传工单数据
            int resultCode = MainControl.updateStatus(maintenanceBean, getContext());
            if (resultCode == INFO_SUCCEED) {
                maintenanceBean.setIsDirty(0);
                maintenanceBean.update(maintenanceBean.getId());
                MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                maintenanceBeanTemp.setIsDirty(0);
                maintenanceBeanTemp.update(maintenanceBean.getId());
            }
            return null;
        }
    }

    //上传时间
    @Subscribe
    public void onEventMainThread(EventCenter.UpdateTime event) {
        MaintenanceBean maintenanceBean = event.getMaintenanceBean();
        new UpdateTimeAsyncTask(maintenanceBean).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    //取消筛选
    @Subscribe
    public void onEventMainThread(EventCenter.CancelSelectDate event) {
        sel_month = "ALL";
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        new MonthSelectAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    //刷新列表
    @Subscribe
    public void onEventMainThread(EventCenter.ReflashList event) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        new MonthSelectAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    //detail返回更新
    @Subscribe
    public void onEventMainThread(EventCenter.UpdateOneRow event) {
        int position = event.getPosition();
        if (position != -1) {
            if (!isfinished) {
                MaintenanceBean maintenanceBean = event.getMaintenanceBean();
                if (null != maintenanceBean && !"COMPLETED".equals(maintenanceBean.getWo_status_code())) {
                    maintenanceBeanList.set(position, maintenanceBean);
                } else {
                    maintenanceBeanList = mainListAdapter.getList();
                    maintenanceBeanList.remove(position);

                }
                mainListAdapter.setList(maintenanceBeanList);
            }
        }
        EventBus.getDefault().post(new EventCenter.ChangeLeftItems());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CAMERA_DANGBAN:
                    // try {
                    // Bitmap bitmap = data.getData();
                    // imageView_takePhoto.setImageBitmap(bitmap);
                    //
                    // } catch (FileNotFoundException e) {
                    // e.printStackTrace();
                    // }
                    dialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        // 消息bus解注
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
